import { message } from 'antd';
import _loadjs from 'loadjs';
import { devModuleCustomFiles } from '../constants/files';

/**
 * 执行事件回调
 *
 * @param {*} callback
 */
const doEventCallback = (callback) => {
  if (callback && typeof callback == 'function') {
    callback();
  }
};

/**
 * 执行事件回调
 *
 * @param {*} eventName
 * @param {*} callback
 */
const doEventSuccess = (eventName, callback) => {
  const _eventRegister = window.eventRegister;
  if (_eventRegister && _eventRegister.startList && typeof _eventRegister.startList == 'function') {
    try {
      _eventRegister.startList(
        eventName,
        () => doEventCallback(callback),
        () => doEventCallback(callback)
      );
    } catch (e) {
      message.error(e.message);
      doEventCallback(callback);
    }
  } else {
    doEventCallback(callback);
  }
};

/**
 * 执行事件
 *
 * 已支持事件类型：
 * 1、登录页加载前：beforLoginRender
 * 2、登录页加载后：afterLoginRender
 * 3、登录前：beforLogin
 * 4、登录成功后：afterLogin
 * 5、主题加载前：beforThemeRender
 * 6、主题加载后：afterThemeRender
 * 7、退出前：beforLogout
 * 8、退出成功后：afterLogout
 *
 * @param {*} eventName
 * @param {*} callback
 */
export const doEvent = (eventName, callback) => {
  const loadjs = window.loadjs || _loadjs;

  loadjs.isDefined('devModuleCustom')
    ? loadjs.ready('devModuleCustom', {
        success: () => doEventSuccess(eventName, callback),
        error: () => doEventSuccess(eventName, callback),
      })
    : loadjs(devModuleCustomFiles, 'devModuleCustom', {
        async: true,
        success: () => doEventSuccess(eventName, callback),
        error: () => doEventSuccess(eventName, callback),
      });
};
